<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use think\Db;

/**
 * 示例接口 123
 */
class Order extends Api{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [''];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    protected $mchid='1603439883';
    protected $appid='wx53530abe753a3cf2';
    protected $apiKey='fdnfjb3856gxhjenklwe09u4395u943u';


    /**
     *  提交信息
     */
    public function applyorder(){

        $user=$this->auth->getUserinfo();

        $data=$this->request->param();

        foreach ($data as $k=>$v){
            if ($v==''){
                $this->error('请填写完整信息');
            }
        }

        $server=Db::name('hospital_service')->where('id',$data['sid'])->find();

        if (!$server){
            $this->error('无服务'.$data['sid']);
        }

        $data['uid']=$user['id'];
        $data['status']=0;
        $data['money']=$server['money'];
        $data['addtime']=time();
        $data['order']=date('ymdHi').rand(1000,9999);


        $order_id=Db::name('order')
            ->insertGetId($data);

        if (!$order_id){
            $this->error('提交失败');
        }


        $this->success('提交成功',$order_id);




    }


    /**
     * 微信支付
     */
    public function pays($order_id,$money)
    {

        $user=$this->auth->getUserinfo();

        $users=Db::name('user')->where('id',$user['id'])->find();

        $appid = $this->appid;
        $mch_id = $this->mchid;
        $key = $this->apiKey; //32位字符

        $nonce_str = 'wp' . date('Ymdhis') . rand(100, 999);
        $zfmoney = $money;

        $log['orderid']=$order_id;
        $log['money']=$zfmoney;
        $log['noncestr']=$nonce_str;
        $log['addtime']=time();

        Db::name('paylog')->insert($log);

        //注意 这里应该要保存下信息  方便回调验证
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';

        $parameters = array(
            'appid' => $appid, //服务商ID
            'mch_id' => $mch_id, //商户号
            'nonce_str' => $nonce_str, //随机字符串
            'body' => '充值',
            'out_trade_no' => $nonce_str,
            'total_fee' => $zfmoney * 100, //分
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'], //终端IP
            'notify_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/api/wxpay/paybackc',  //回调
            'openid' => $users['openid'], //用户openid
            'trade_type' => 'JSAPI'//交易类型
        );



        //统一下单签名
        $parameters['sign'] = getSign($parameters, $key);
        $xmlData = arrayToXml($parameters);


        $return = xmlToArray(postXmlCurl($xmlData, $url, 60));

        if (!isset($return['result_code'])){
            $this->error($return['return_msg']);
        }

        $parameter = array(
            'appId' => $appid, //小程序ID
            'timeStamp' => '' . time() . '', //时间戳
            'nonceStr' => $nonce_str, //随机串
            'package' => 'prepay_id=' . $return['prepay_id'], //数据包
            'signType' => 'MD5'//签名方式
        );
        //签名
        $parameter['paySign'] = getSign($parameter, $key);


        $this->success('支付信息', $parameter);


    }

    /**
     * 订单列表
     */
    public function getorderlist(){

        $user=$this->auth->getUserinfo();
        $status=$this->request->param('status');

        $map['o.uid']=['eq',$user['id']];

        if ($status>-1){
            $map['o.status']=['eq',$status];
        }

        $lists=Db::name('order')->alias('o')
            ->join('hospital_service hs','o.sid=hs.id')
            ->where($map)
            ->order('id desc')
            ->field('o.*,hs.image as himage,hs.name as hsname')
            ->select();

        foreach ($lists as &$val){

            $val['hsimage']=cdnurl($val['himage'], true);

            $hospital=Db::name('hospital')->where('id',$val['hid'])->find();

            $val['hpname']=$hospital['name'];

            $down=Db::name('user_down')->where('id',$val['did'])->find();

            $val['dname']=$down['name'];
            $val['dyear']=$down['year'];

        }

        $this->success('订单列表', $lists);


    }

    /**
     * 删除信息
     */
    public function deletebyid()
    {

        $id = $this->request->param('id');

        $result = Db::name('order')->where('id', $id)->delete();

        if ($result) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    //支付订单
    public function paybyid(){

        $id = $this->request->param('id');

        $order=Db::name('order')->where(['id'=>$id])->find();

        $this->pays($id,$order['money']);


    }

    /**
     * 订单详情
     */
    public function getorderbyid()
    {
        $id = $this->request->param('id');

        $order=Db::name('order')->alias('o')
            ->join('hospital_service hs','o.sid=hs.id')
            ->where(['o.id'=>$id])
            ->field('o.*,hs.image as himage,hs.name as hsname')
            ->find();


        $array[]=['label'=>'1','text'=>'提交信息','active'=>true];
        $array[]=['label'=>'2','text'=>'在线支付','active'=>false];
        $array[]=['label'=>'3','text'=>'服务中','active'=>false];
        $array[]=['label'=>'4','text'=>'服务完成','active'=>false];

        if ($order['status']==0){
            $array[1]['active']=false;
            $array[2]['active']=false;
            $array[3]['active']=false;
        }

        if ($order['status']==1){
            $array[1]['active']=true;
            $array[2]['active']=false;
            $array[3]['active']=false;
        }

        if ($order['status']==2){
            $array[1]['active']=true;
            $array[2]['active']=true;
            $array[3]['active']=false;
        }

        if ($order['status']>2){
            $array[1]['active']=true;
            $array[2]['active']=true;
            $array[3]['active']=true;
        }

        $hospital=Db::name('hospital')->where('id',$order['hid'])->find();

        $order['hpimage']=cdnurl($hospital['image'], true);
        $order['hpname']=$hospital['name'];

        $down=Db::name('user_down')->where('id',$order['did'])->find();
        $order['dname']=$down['name'];
        $order['dmobile']= $down['mobile'];
        $order['dyear']= $down['year'];

        $worker=Db::name('worker')->where('id',$order['wid'])->find();
        $order['wname']=$worker['name'];
        $order['wmobile']= $order['status']>0&&$order['status']<4?$worker['mobile']: substr($worker['mobile'],0,3).'****'.substr($worker['mobile'],7,4);


        $this->success('订单详情', ['order'=>$order,'array'=>$array]);

    }

    //退款
    public function backmoney()
    {

        $id = $this->request->param('id');
        $this->success('退款成功');

    }

    /**
     * 退款
     * @param float $totalFee 订单金额 单位元
     * @param float $refundFee 退款金额 单位元
     * @param string $refundNo 退款单号
     * @param string $wxOrderNo 微信订单号
     * @param string $orderNo 商户订单号
     * @return string
     */
    public function doRefund() {


        $id=$this->request->param('oid');
        $types=$this->request->param('types');

        $order=Db::name('order')->where(['id'=>$id])->find();

        $pay=Db::name('paylog')
            ->where(['orderid'=>$id])
            ->where(['status'=>1])
            ->where(['types'=>0])->find();

        if (!$pay){
            $this->error('无法退款');
        }

        $totalFee=$pay['money'];
        $refundFee=$pay['money'];
        $wxOrderNo=$pay['noncestr'];


        $last=0;
        if ($types==1){
            $refundFee=$totalFee*0.8;

            $last=$totalFee-$refundFee;
        }

        $config = array(
            'mch_id' => $this->mchid,
            'appid' =>$this->appid,
            'key' => $this->apiKey,
        );

        $unified = array(
            'appid' => $config['appid'],
            'mch_id' => $config['mch_id'],
            'nonce_str' =>$pay['noncestr'] ,
            'total_fee' => intval($totalFee * 100), //订单金额  单位 转为分
            'refund_fee' => intval($refundFee * 100), //退款金额 单位 转为分
            'sign_type' => 'MD5', //签名类型 支持HMAC-SHA256和MD5，默认为MD5
            'transaction_id' => $pay['wxid'], //微信订单号
            'out_trade_no' => $pay['noncestr'] , //商户订单号
            'out_refund_no' => uniqid(), //商户退款单号
            'refund_desc' => '其他' //退款原因（选填）
        );


        $unified['sign'] = getSign($unified, $config['key']);

        $xml=arrayToXml($unified);


        $responseXml = $this->curlPost('https://api.mch.weixin.qq.com/secapi/pay/refund',$xml);

        $unifiedOrder = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);


        $jsonStr = json_encode($unifiedOrder);
        $jsonArray = json_decode($jsonStr,true);




        if ($jsonArray['result_code']=='SUCCESS'){

            Db::name('order')->where(['id'=>$id])
                ->update(['status'=>4,'backmoney'=>$refundFee]);

            Db::name('paylog')->where(['orderid'=>$id])
                ->update(['types'=>1]);


            $worker=Db::name('worker')->where('id',$order['wid'])->find();

            if ($types==1){
                moneyadd($worker['user_id'],$last,'退款');
            }


            Smslib::notice($worker['mobile'], '', '2504693');

            $this->success($jsonArray['return_msg']);
        }else{

            $this->error($jsonArray['err_code_des']);
        }


    }


    public function curlPost($url = '', $postData = '', $options = array()) {

        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //第一种方法，cert 与 key 分别属于两个.pem文件

        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT, './apiclient_cert.pem');//绝对路径
        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY, './apiclient_key.pem');//绝对路径

        $data = curl_exec($ch);


        return $data;

    }



}
